package com.config;

import com.pojo.UserInfo;
import com.service.UserInferService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserInferService service;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进入未授权的页面时就会进入这个方法！");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.addStringPermission("user:add");
        /*拿到当前登录的对象*/
        Subject subject = SecurityUtils.getSubject();
        UserInfo currentUser = (UserInfo) subject.getPrincipal();//拿到user对象
        //设置当前用户的权限（从数据库中取出）
       info.addStringPermission(currentUser.getPerms());
        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了——》doGetAuthenticationInfo");
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        /*String username="root";
        String password="123456";*/
        UserInfo user = service.queryUserByname(userToken.getUsername());
        if (user==null)
           return null;


       /* if (!userToken.getUsername().equals(username))
            return null;//return null 的作用就是抛出UnknownAccountException 异常*/
        //接下来就是密码认证，但是shiro自动帮我们做了
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
